package com.gh.ok.ui

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.gh.ok.R
import com.gh.ok.databinding.ActivityFlowSampleBinding
import com.gh.ok.viewmodel.HttpSampleViewModel
import com.gyf.immersionbar.ktx.immersionBar
import com.ok.common.base.BaseVMActivity
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

class FlowSampleActivity : BaseVMActivity<HttpSampleViewModel, ActivityFlowSampleBinding>() {

    private val progressList = listOf("第1个进度条", "第2个进度条", "第3个进度条")

    override fun initImmersionBar() {
        immersionBar {
            titleBar(mBinding.viewTitle.titleBar)
            navigationBarColor(R.color.bgHomeTab)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.apply {
            viewTitle.tvTitle.text = intent.extras?.getString("title")
        }
        lifecycleScope.launch {
            progressList.asFlow()
                .onStart {
                    delay(1000)
                }
                .collect { it ->
                    val index = progressList.indexOf(it)
                    flow {
                        for (i in 1..100) {
                            delay(20)
                            emit(i)
                        }
                    }.collect {
                        when (index) {
                            0 -> {
                                mBinding.pv1.progress = it.toFloat()
                            }

                            1 -> {
                                mBinding.pv2.progress = it.toFloat()
                            }

                            2 -> {
                                mBinding.pv3.progress = it.toFloat()
                            }
                        }
                    }
                    delay(200)
                }
        }
    }

    override fun initListener() {
        super.initListener()
        mBinding.viewTitle.ibtnBack.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.ibtn_back -> {
                finish()
            }
        }
    }

}